package services

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"strings"
	"time"

	"cashew.com/cashew_api/models"
	"cashew.com/cashew_common/constants"
	"cashew.com/cashew_common/utils"
	"github.com/beego/beego/v2/core/logs"
)

type PageRequest struct {
	StartPage    int
	CurrentPage  int
	HomeRedisKey string
}

// 声明不同地区时区和北京时间的差距
var ratingMap = map[int]string{
	0: "C",
	1: "C",
	2: "B",
	3: "A",
	4: "S",
}

const (
	defaultCountryCode string = "MOREN"
)

// 国家编码合法值集合（后续新增只需在此扩展）
var allowedCountryCodes = map[string]struct{}{
	"ID": {},
	"CN": {},
}

func ValidateCountryCode(code string) string {
	// 统一转换为大写处理（根据需求调整）
	normalized := strings.ToUpper(strings.TrimSpace(code))

	// 检查是否在合法集合中
	if _, ok := allowedCountryCodes[normalized]; ok {
		return normalized
	}

	// 默认值
	return defaultCountryCode
}

// 获取男性首页数据
func GetMalePage(userId int64, countryCode string, startPage int, currentPage int) (map[string]interface{}, error) {

	userTag, err := GetUserTag(userId)
	if err != nil {
		return nil, err
	}

	// 默认给一个标签，不至于没数据返回
	if userTag == "" {
		userTag = "OLD_USER"
	}

	countryCode = ValidateCountryCode(countryCode)

	return getCommonPageData(PageRequest{
		HomeRedisKey: constants.HOME_REDIS_KEY_PREFIX_MALE + strings.ToUpper(userTag) + "::" + countryCode,
		StartPage:    startPage,
		CurrentPage:  currentPage,
	})
}

// 获取女性首页数据
func GetFemalePage(anchorId int64, countryCode string, startPage int, currentPage int) (map[string]interface{}, error) {
	anchorRatingStr := "C" // 默认给一个评级，不至于没数据返回
	anchorRating, err := GetAnchorRating(anchorId)
	if err == nil && anchorRating > 0 {
		if _, exists := ratingMap[anchorRating]; exists {
			anchorRatingStr = ratingMap[anchorRating]
		}
	}

	countryCode = ValidateCountryCode(countryCode)

	return getCommonPageData(PageRequest{
		HomeRedisKey: constants.HOME_REDIS_KEY_PREFIX_FEMALE + anchorRatingStr + "::" + countryCode,
		StartPage:    startPage,
		CurrentPage:  currentPage,
	})
}

type CashewV1ListStat struct {
	ActiveCount int `json:"active_count"`
	AllCount    int `json:"all_count"`
}

// 获取首页数据公共函数
func getCommonPageData(req PageRequest) (res map[string]interface{}, err error) {

	// 构造 Redis 键
	redisServer := new(utils.RedisService)
	homeRedisStatKey := req.HomeRedisKey + "::STAT"
	homeRedisKey := req.HomeRedisKey

	logs.Debug("homeRedisStatKey:%s", homeRedisStatKey)

	// 获取统计信息
	activeCount := 0
	allCount := 0
	pageListStatStr, err := redisServer.Get(homeRedisStatKey)
	if err != nil {
		logs.Error("redisServer.Get(%s) result is not int", homeRedisStatKey)
		return nil, err
	}

	if pageListStatStr != "" {
		// 解析 json ,把 pageListStatStr 解析成 pageListStat 结构体
		pageListStat := &CashewV1ListStat{}
		err = json.Unmarshal([]byte(pageListStatStr), &pageListStat)
		if err != nil {
			logs.Error("json.Unmarshal(%s): %v", pageListStat, err)
			return nil, err
		}

		activeCount = pageListStat.ActiveCount
		allCount = pageListStat.AllCount
	}

	// 初始化分页
	if req.StartPage == 0 {
		req.StartPage = GetRandomInt(1, activeCount)
		req.CurrentPage = req.StartPage
	}

	// 设置返回分页信息
	res = make(map[string]interface{})
	hasNext, startPageRes, nextPage := GetPageNum(req.StartPage, req.CurrentPage, activeCount, allCount)
	res["has_next"] = hasNext
	res["start_page"] = startPageRes
	res["next_page"] = nextPage

	if allCount == 0 {
		logs.Warning("获取首页数据失败：all_count is 0")
		res["data"] = nil
		return res, nil
	}

	// 查询当前页数据
	currentPageIndex := req.CurrentPage - 1
	result := redisServer.HGet(homeRedisKey, fmt.Sprintf("%d", currentPageIndex))
	if result == "" {
		logs.Warning("获取首页数据失败：redisserver.Hget(%s, %s) result is empty", homeRedisKey, fmt.Sprintf("%d", currentPageIndex))
		res["data"] = nil
		return res, nil
	}

	// 解析 JSON
	jsonData := make(map[string]interface{})
	if err = json.Unmarshal([]byte(result), &jsonData); err != nil {
		logs.Error("json.Unmarshal(%s): %v", result, err)
		return nil, err
	}

	// 检查 jsonData["data"] 是否存在
	if data, exists := jsonData["data"]; exists {
		res["data"] = data
	} else {
		// 如果不存在，可以设置默认值或记录日志
		logs.Warn("jsonData[\"data\"] does not exist")
		res["data"] = nil // 或者设置其他默认值
	}

	if flagImagePrefix, exists := jsonData["flag_image_prefix"]; exists {
		res["flag_image_prefix"] = flagImagePrefix
	}
	//if pageNumber, exists := jsonData["page_number"]; exists {
	//res["page_number"] = pageNumber
	res["page_number"] = req.CurrentPage
	//}
	if count, exists := jsonData["count"]; exists {
		res["count"] = count
	}

	logs.Debug("result:%s", result)
	logs.Debug("res:%+v \n", res)

	return res, nil
}

// 获取用户标签
func GetUserTag(userId int64) (tag string, err error) {
	userInfo, err := models.GetUser_profileByUserId(userId)
	if err != nil {
		return "", err
	}

	return userInfo.Tag, nil
}

// 获取主播评分
func GetAnchorRating(anchorId int64) (rating int, err error) {
	anchorInfo, err := models.GetAnchor_infoByAnchorId(anchorId)
	if err != nil {
		return 0, err
	}

	return anchorInfo.Rating, nil
}

func GetRandomInt(min, max int) int {

	if min >= max {
		return min
	}
	// 设置随机数种子
	rand.Seed(time.Now().UnixNano())
	return min + rand.Intn(max-min)
}

func GetPageNum(startPage int, currentPage int, activeCount int, allCount int) (hasNext bool, startPageRes int, nextPage int) {
	hasNext = true

	if currentPage >= startPage {
		if currentPage < activeCount {
			nextPage = currentPage + 1
		} else if currentPage == activeCount {
			if startPage == 1 {
				nextPage = currentPage + 1
			} else {
				nextPage = 1
			}
		} else {
			nextPage = currentPage + 1
		}
	} else if currentPage == startPage-1 {
		nextPage = activeCount + 1
	} else {
		nextPage = currentPage + 1
	}

	if currentPage >= allCount {
		hasNext = false
	}

	startPageRes = startPage
	return
}
